package soar.test.xml.jdk;

import java.io.ByteArrayInputStream;
import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class App
{
    public static void main(String[] args)
    {
        if (args.length < 1)
        {
            System.out.println(String.format("argument error"));
            return;
        }
        new App().run(args[0]);
    }

    private void run(String xmldir)
    {
        try
        {
            String split = "================================================";
            System.out.println(split);

            parse(xmldir);
            System.out.println(split);
            
            parse_string();
            System.out.println(split);
        }
        catch (Exception e)
        {
            System.err.println(String.format("fail: %s", e));
        }
    }

    private void parse(String xmldir) throws Exception
    {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(new File(xmldir + "/data.xml"));

        XPathFactory pf = XPathFactory.newInstance();
        XPath path = pf.newXPath();

        NodeList persons = (NodeList) path.evaluate("root/person", doc,
                XPathConstants.NODESET);
        for (int i = 0; i < persons.getLength(); i++)
        {
            Node person = persons.item(i);
            System.out.println(String.format("%s[%d]: %s", "person", i,
                    person.getNodeName()));
            NamedNodeMap attrs = person.getAttributes();
            for (int j = 0; j < attrs.getLength(); j++)
            {
                Node attr = attrs.item(j);
                if (attr.getNodeName().equals("id"))
                {
                    System.out.println(String.format("    %s: %s",
                            attr.getNodeName(), attr.getTextContent()));
                }

            }
            NodeList items = person.getChildNodes();
            for (int j = 0; j < items.getLength(); j++)
            {
                Node item = items.item(j);
                if (item.getNodeName().equals("username"))
                {
                    System.out.println(String.format("    %s: %s",
                            item.getNodeName(), item.getTextContent()));
                }
                else if (item.getNodeName().equals("password"))
                {
                    System.out.println(String.format("    %s: %s",
                            item.getNodeName(), item.getTextContent()));
                }
            }
        }

        NodeList computers = (NodeList) path.evaluate("root/computer", doc,
                XPathConstants.NODESET);
        for (int i = 0; i < computers.getLength(); i++)
        {
            Node computer = computers.item(i);
            System.out.println(String.format("computer[%d]:", i));
            NamedNodeMap attrs = computer.getAttributes();
            String type = attrs.getNamedItem("type").getTextContent();
            System.out.println("    type: " + type);
            // for (int j = 0; j < attrs.getLength(); j++)
            // {
            // Node attr = attrs.item(j);
            // if (attr.getNodeName().equals("type"))
            // {
            // type = attr.getTextContent();
            // }
            // }
            // System.out.println("    type: " + type);
            NodeList computer_children = computer.getChildNodes();
            for (int j = 0; j < computer_children.getLength(); j++)
            {
                Node computer_child = computer_children.item(j);
                if (computer_child.getNodeName().equals("user"))
                {
                    if (type.equalsIgnoreCase("pc"))
                    {
                        System.out.println("        user: "
                                + computer_child.getTextContent());
                    }
                    else
                    {
                        System.out.println("        user:");
                        NodeList server_children = computer_children.item(j)
                                .getChildNodes();
                        for (int k = 0; k < server_children.getLength(); k++)
                        {
                            Node server_child = server_children.item(k);
                            if (server_child.getNodeName().equals("account"))
                            {
                                System.out.println("            account: "
                                        + server_child.getTextContent());
                            }
                        }
                    }
                }
            }
        }
    }

    private void parse_string() throws Exception
    {
        String input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
                + "<rss version=\"2.0\"><respCode>0000</respCode><respMesg>处理成功</respMesg><planNo>88841</planNo><orderNo></orderNo><issueNo></issueNo><betToken></betToken><openTime></openTime><walletInfo><balance></balance><freezeAmount></freezeAmount><historyConsumption></historyConsumption><sinaPayBalance></sinaPayBalance><giftBalance></giftBalance><freezeSinaPayBalance></freezeSinaPayBalance><freezeGiftBalance></freezeGiftBalance></walletInfo></rss>";
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(new ByteArrayInputStream(input.getBytes("UTF-8"))); // 要指明字符集，不同平台有缺省字符集

        XPathFactory pf = XPathFactory.newInstance();
        XPath path = pf.newXPath();
    }
}
